package com.ruoyi.web.controller.course;

import java.io.File;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.constant.SysConstants;
import com.ruoyi.common.utils.ObjectUtil;
import com.ruoyi.questionBank.domain.Question;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.course.domain.SysCourse;
import com.ruoyi.course.service.ISysCourseService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 课程Controller
 * 
 * @author YJF
 * @date 2023-05-17
 */
@RestController
@RequestMapping("/course/course")
public class SysCourseController extends BaseController
{
    @Autowired
    private ISysCourseService sysCourseService;

    @GetMapping("/examQuestion")
    public AjaxResult getCourseExamQuestion(Long courseNo){
        ObjectUtil.checkNull(courseNo ,"courseNo");
        List<Question> list = sysCourseService.getCourseExamQuestion(courseNo);
        return AjaxResult.success(list);
    }

    /**
     * 查询课程列表
     */
    @PreAuthorize("@ss.hasPermi('course:course:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysCourse sysCourse)
    {
        startPage();
        List<SysCourse> list = sysCourseService.selectSysCourseList(sysCourse);
        return getDataTable(list);
    }

    /**
     * 查询全部课程列表
     */
    @PreAuthorize("@ss.hasPermi('course:course:list')")
    @GetMapping("/wholeList")
    public AjaxResult wholeList(SysCourse sysCourse)
    {
        return AjaxResult.success(sysCourseService.selectWholeList(sysCourse));
    }

    /**
     * 导出课程列表
     */
    @PreAuthorize("@ss.hasPermi('course:course:export')")
    @Log(title = "课程", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysCourse sysCourse)
    {
        List<SysCourse> list = sysCourseService.selectSysCourseList(sysCourse);
        ExcelUtil<SysCourse> util = new ExcelUtil<SysCourse>(SysCourse.class);
        util.exportExcel(response, list, "课程数据");
    }

    /**
     * 获取课程详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:course:query')")
    @GetMapping(value = "/{courseId}")
    public AjaxResult getInfo(@PathVariable("courseId") Long courseId)
    {
        return AjaxResult.success(sysCourseService.selectSysCourseByCourseId(courseId));
    }

    /**
     * 新增课程
     */
    @PreAuthorize("@ss.hasPermi('course:course:add')")
    @Log(title = "课程", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysCourse sysCourse)
    {
        //课程名称唯一
//        if (SysConstants.CONSTANT_STR1.equals(sysCourseService.checkCourseNameUnique(sysCourse)))
//        {
//            return AjaxResult.error("新增课程：'" + sysCourse.getCourseName() + "'失败，名称已存在");
//        }
        return toAjax(sysCourseService.insertSysCourse(sysCourse));
    }

    /**
     * 修改课程
     */
    @PreAuthorize("@ss.hasPermi('course:course:edit')")
    @Log(title = "课程", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysCourse sysCourse)
    {
        //名称+分类唯一
        if (SysConstants.CONSTANT_STR1.equals(sysCourseService.checkCourseNameUnique(sysCourse)))
        {
            return AjaxResult.error("新增课程：'" + sysCourse.getCourseName() + "'失败，名称已存在");
        }
        return toAjax(sysCourseService.updateSysCourse(sysCourse));
    }

    /**
     * 删除课程
     */
    @PreAuthorize("@ss.hasPermi('course:course:remove')")
    @Log(title = "课程", businessType = BusinessType.DELETE)
	@DeleteMapping("/{courseIds}")
    public AjaxResult remove(@PathVariable Long[] courseIds)
    {
        return toAjax(sysCourseService.deleteSysCourseByCourseIds(courseIds));
    }

    @PreAuthorize("@ss.hasPermi('course:course:upload')")
    @Log(title = "课程", businessType = BusinessType.IMPORT)
    @RequestMapping("/uploadVideo/{courseNo}")
    public AjaxResult uploadVideo(@PathVariable("courseNo") Long courseNo ,MultipartFile file) throws Exception{
        sysCourseService.uploadVideo(courseNo ,file.getInputStream());
        return  AjaxResult.success();
    }

    @RequestMapping("/playVideo")
    public void playVideo(long courseNo , HttpServletRequest req , HttpServletResponse response) throws Exception{
        String path = sysCourseService.getVideoPath(courseNo);
        readVideo(new File(path) ,req ,response);
    }

    public void readVideo(File file , HttpServletRequest req , HttpServletResponse response) throws Exception{
        long fl = file.length();

        String rangeStr = req.getHeader("Range");
        long range = 0L;
        if(StrUtil.isNotBlank(rangeStr)){
            range = Long.parseLong(rangeStr.substring(rangeStr.indexOf("=") + 1 ,rangeStr.indexOf("-")));
        }
        response.setHeader("Content-type", "video/mp4");
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

        RandomAccessFile randomAccessFile = new RandomAccessFile(file ,"r");
        randomAccessFile.seek(range);
        byte[] bytes = new byte[1024 * 1024];
        int len = randomAccessFile.read(bytes);
        response.setContentLength(len);
        response.setHeader("Content-Range", "bytes " + range + "-" + (fl - 1) + "/" + fl);

        OutputStream os = response.getOutputStream();
        os.write(bytes, 0 ,len);
        os.close();
        randomAccessFile.close();
    }
}
